package com.taobao.protobuf.perference;

import java.io.File;

import org.eclipse.jface.preference.FieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.FileFieldEditor;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;

import com.taobao.protobuf.Activator;

public class PBPerferencePage extends FieldEditorPreferencePage implements
		IWorkbenchPreferencePage {

	private FileFieldEditor fileFieldEditor = null;
	public PBPerferencePage(){
		super(GRID);
		setPreferenceStore(Activator.getDefault().getPreferenceStore());
	}
	@Override
	public void init(IWorkbench workbench) {
	}

	@Override
	protected void createFieldEditors() {
		fileFieldEditor = new FileFieldEditor("protoc", "protoc compiler path:", getFieldEditorParent());
		addField(fileFieldEditor);
	}
	@Override
	protected void checkState() {
		super.checkState();
		if(!isValid()){
			return ;
		}
		String value = fileFieldEditor.getStringValue();
		if(value == null || value.length() == 0){
			setErrorMessage("Protoc compiler path is null!");
			setValid(false);
		}else {
			File f = new File(value);
			if(!f.exists()){
				setErrorMessage("File "+value+" not exist!");
				setValid(false);
			}else{
				setErrorMessage(null);
				setValid(true);
			}
		}
	}

	@Override
	public void propertyChange(PropertyChangeEvent event) {
		super.propertyChange(event);
		if(event.getProperty().equals(FieldEditor.VALUE)){
			if(event.getSource() == fileFieldEditor){
				checkState();
			}
		}
	}
}
